package com.road7.mina.simpledemo;

import java.util.Date;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

//首先定义一个业务逻辑处理器TimeServerHandler，继承自IoHandlerAdapter，
//实现的功能有：当客户端创建会话时会显示客户端设备的IP和端口；
//当客户端输入quit时结束会话；客户端输入其它内容时则向客户端发送当前时间。
public class TimeServerHandler extends IoHandlerAdapter {

	@Override
	public void sessionCreated(IoSession session) throws Exception {

		System.out.println("1. server sessionCreated");
		System.out.println(session.getRemoteAddress().toString());
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		System.out.println("3. server messageReceived");
		String msg = message.toString();
		System.out.println(msg);
		if ("quit".equalsIgnoreCase(msg.trim())) {
			session.close(true);
			return;
		}
		Date date = new Date();
		session.write(date.toString());// 返回当前时间的字符串
		System.out.println("Message written...");
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		System.out.println("5.server sessionClosed");
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		System.out.println("4.server sessionIdle" + status);
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		System.out.println("2.server sessionOpened");
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		cause.printStackTrace();
	}

}
